package cn.cosmosx.base.security.service;

import cn.cosmosx.base.constant.ResultCode;
import cn.cosmosx.base.exception.PlatformException;
import cn.cosmosx.base.security.entity.SecurityUserVo;
import cn.cosmosx.base.util.BeanUtil;
import cn.cosmosx.base.util.FastHandlerUtils;
import cn.cosmosx.entity.sys.SysPerms;
import cn.cosmosx.entity.sys.SysRole;
import cn.cosmosx.entity.vo.UserVO;
import cn.cosmosx.service.sys.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.stream.Collectors;

/**
 * UserDetailsService根据用户名查找用户。在实际实现中，根据实现实例的配置方式，
 * 搜索可能区分大小写，也可能不区分大小写。在这种情况下，返回的UserDetails对象可能具有不同于实际请求的用户名。
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserService userService;

    @Override
    public SecurityUserVo loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVO user = userService.getRolesAndPermsById(null, username);
        return FastHandlerUtils.notNullCallBackElseThrow(user, () -> {
            SecurityUserVo bean = BeanUtil.copyProperties(new SecurityUserVo(), user);
            Optional.ofNullable(user.getRoles()).ifPresent(roles -> bean.setRoles(roles.stream().map(SysRole::getRoleCode).collect(Collectors.toSet())));
            Optional.ofNullable(user.getPerms()).ifPresent(roles -> bean.setPerms(roles.stream().map(SysPerms::getPermUrl).collect(Collectors.toSet())));
            return bean;
        }, () -> new PlatformException(ResultCode.U90002));
    }
}
